<?php
/* -------------------------------------------------------------------------
 * Nom du fichier : login.php
 * Fichier valider : 07/11/12 13:38
 * -------------------------------------------------------------------------
 */

include(SITE_ROOT . '/inc/class_db.php');

function boxlogin() { 
	?>
		<section id="loginbox">
			<div id="authbox">
				<form  method="post" action="<?=SITE_ROOT?>/front/auth.php" autocomplete="on"> 
					<p> 
						<label for="username" class="uname" data-icon="u">Nom d'utilisateur :</label>
						<input id="username" name="username" required="required" type="text" placeholder="Ton nom"/>
					</p>
					<p> 
						<label for="password" class="youpasswd" data-icon="p">Mot de passe :</label>
						<input id="password" name="password" required="required" type="password" placeholder="Ton mot de passe" /> 
					</p>
					<p class="keeplogin"> 
						<input type="checkbox" name="loginkeeping" id="loginkeeping" /> 
						<label for="loginkeeping">Se souvenir de moi</label>
					</p>
					<p class="login button"> 
						<input type="submit" value="Login" /> 
					</p>
				</form>
			</div>
	   </section>
	<?
}

function alreadylogin() {
        if ( (!empty($_SESSION['login']) || (!empty($_COOKIE['cookie_login'])) )) {
		$dest = SITE_ROOT."/front/accueil.php";
                header("Location:$dest");
	}
}

function boxlogout() {
	?>
	<head>
	<META http-equiv="Refresh" content="5">
	</head>
	<section id="loginbox">
		<div id="errorbox" class="animate form">
			<p>
				<h2>Tu n'es plus connecté...</h2>
			</p>
			<p class="login button"> 
						<input type="submit" value="continuer" onclick="location.href='<?=SITE_ROOT?>/index.php'"/> 
			</p>
		</div>
	</section>
	<?
}

function createauthvar() {
	//Ouvre la connexion à la base de donnée
	$db = New Database;

	// Passage login en session
	$_SESSION['login'] = $_POST['username'];

	// Passage login en cookie
	if (isset($_POST['loginkeeping'])) {
		if ($_POST['loginkeeping'] == 'on') {
			setcookie('cookie_login', $_SESSION['login'], (time() + 86400));
		}
	}
}

function clearauthvar() {
	// Clear cookie et session
	setcookie('cookie_login');
	session_destroy();
}

function checkauthcredential() {
	//Ouvre la connexion à la base de donnée
	$db = New Database;
	
	//Requete SQL
	$sql = "SELECT * FROM users WHERE `nom`='".$_POST['username']."' AND `pwd`='".sha1($_POST['password'])."'";

	$ua=getBrowser();
	
	//Test si login et pwd sont valide sinon redirect vers page d'erreur
	if ($db->select_query($sql)) {
		$sql = "INSERT INTO `authlog` VALUES ('', NOW(),'".$_POST['username']."','".sha1($_POST['password'])."', '".$_SERVER["REMOTE_ADDR"]."', '".$ua['name']."', '".$ua['platform']."', 'ok')";
		if (!@$db->iud_query($sql)) {
			$msg = error_get_last ();
			$error = 2;
			$msg = $msg['message'];
			$result = array($error, $msg);
			return $result;
		}
		header("Location:accueil.php");
	}
	else {
		$sql = "INSERT INTO `authlog` VALUES ('', NOW(),'".$_POST['username']."','".$_POST['password']."', '".$_SERVER["REMOTE_ADDR"]."', '".$ua['name']."', '".$ua['platform']."', 'Error')";
		if (!@$db->iud_query($sql)) {
			$msg = error_get_last ();
			$error = 2;
			$msg = $msg['message'];
			$result = array($error, $msg);
			return $result;
		}
		// Clear cookie et session
		setcookie('cookie_login');
		session_destroy();
		?>	
		<section id="loginbox">
			<div id="errorbox" class="animate form">
				<p>
					<h2>Désolé</h2>
				</p>
				<p>Tes informations de connexion ne sont pas correctes !</p>
				<p class="login button">
					<input type="submit" value="Réssayer" onclick="location.href='<?=SITE_ROOT?>/index.php'"/>
				</p>
			</div>
		</section>
		<?
	}
}

function getBrowser() 
{ 
    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/android/i', $u_agent)) {
        $platform = 'android';
    }
    elseif (preg_match('/ipad/i', $u_agent)) {
        $platform = 'ipad';
    }
    elseif (preg_match('/iphone/i', $u_agent)) {
        $platform = 'iphone';
    }
    elseif (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
    
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'Internet Explorer'; 
        $ub = "MSIE"; 
    } 
    elseif(preg_match('/Firefox/i',$u_agent)) 
    { 
        $bname = 'Mozilla Firefox'; 
        $ub = "Firefox"; 
    } 
    elseif(preg_match('/Chrome/i',$u_agent)) 
    { 
        $bname = 'Google Chrome'; 
        $ub = "Chrome"; 
    } 
    elseif(preg_match('/Safari/i',$u_agent)) 
    { 
        $bname = 'Apple Safari'; 
        $ub = "Safari"; 
    } 
    elseif(preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'Opera'; 
        $ub = "Opera"; 
    } 
    elseif(preg_match('/Netscape/i',$u_agent)) 
    { 
        $bname = 'Netscape'; 
        $ub = "Netscape"; 
    } 
    
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
    
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
    
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
    
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}
